package com.windowes.weichang.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.windowes.weichang.access.UserContext;
import com.windowes.weichang.common.Const;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.component.jpush.JPushService;
import com.windowes.weichang.component.redis.RedisService;
import com.windowes.weichang.dao.*;
import com.windowes.weichang.dto.*;
import com.windowes.weichang.pojo.*;
import com.windowes.weichang.utils.DateTimeUtil;
import com.windowes.weichang.utils.RegexUtils;
import com.windowes.weichang.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/6/1 上午8:42
 * @description:
 *
 **/
@Service
@Slf4j
public class DemandService {

    public static CopyOnWriteArrayList<String> types = new CopyOnWriteArrayList<String>();

    static {
        types.add("11");
        types.add("12,13");
    }


    @Autowired
    DemandMapper demandMapper;
    @Autowired
    DemandItemMapper itemMapper;
    @Autowired
    DemandItemMediaMapper mediaMapper;
    @Autowired
    DemandArrivalMapper arrivalMapper;
    @Autowired
    DemandProjectMapper projectMapper;
    @Autowired
    DemandCommentMapper demandCommentMapper;
    @Autowired
    JPushService pushService;
    @Autowired
    WUserMapper userMapper;
    @Autowired
    WShopMapper shopMapper;
    @Autowired
    OrderStatusMapper orderStatusMapper;
    @Autowired
    DemandOperateLogMapper demandOperateLogMapper;
    @Autowired
    ShopUserRelationMapper shopUserRelationMapper;
    @Autowired
    RedisService redisService;
    @Autowired
    SysMapper sysMapper;
    @Autowired
    DemandCancleLogMapper demandCancleLogMapper;
    @Autowired
    DemandCustomerPayFlowMapper demandCustomerPayFlowMapper;
    @Autowired
    DemandShopPayFlowMapper demandShopPayFlowMapper;
    @Autowired
    MessageService messageService;
    @Autowired
    PayService payService;

    @Autowired
    DemandTalkMapper talkMapper;


    /**
     * 客户发起订单
     *
     * @param demand
     * @return
     */
    @Transactional
    public ServerResponse saveOrUpdate(Demand demand) {
        if (demand == null) {
            return ServerResponse.createByErrorMessage("请提交需求信息");
        }

        if (!RegexUtils.isMobileExact(demand.getPhone())) {
            return ServerResponse.createByErrorMessage("请输入正确手机号！");
        }

        WUser user = UserContext.getUser();
        //普通用户强制不允许设置状态
        demand.setStatus(null);
        Integer deptId = UserContext.getDeptId();
        demand.setDeptId(deptId);
        String content = null;
        if (demand.getId() == null) {
            demand.setOrderNo(UUIDUtil.getOrderNo());
            demandMapper.insertSelective(demand);
            content = "初始操作,用户【" + user.getName() + "】提交订单!";
        } else {
            demandMapper.updateByPrimaryKeySelective(demand);
            content = "用户【" + user.getName() + "】更新订单!";
        }
        //添加操作流水记录
        insertOperateLog(demand.getId(), user.getId(), content);
        DemandItemDto dto = new DemandItemDto();
        DemandItem demandItem = new DemandItem();
        demandItem.setDemandId(demand.getId());
        dto.setItem(demandItem);
        addDemandItem(dto);


        return ServerResponse.createBySuccessMessage("提交成功！");
    }

    /**
     * 添加操作流水记录
     *
     * @param demandId
     * @param userId
     * @param content
     */
    private void insertOperateLog(Integer demandId, Integer userId, String content) {
        DemandOperateLog demandLog = DemandOperateLog.createLog(content, userId, demandId);
        demandOperateLogMapper.insertSelective(demandLog);
    }

    /**
     * @param pageNo
     * @param pageSize
     * @return
     */
    public ServerResponse listForShopkeeper(Short status, Integer shopId, int pageNo, int pageSize, String keyword, String type) {
        Page<Demand> page = new Page<>(pageNo, pageSize);
        page.setRecords(demandMapper.selectByPage(page, null, shopId, status, keyword, type));
        return ServerResponse.createBySuccess(page);
    }


    /**
     * 平台查询订单
     *
     * @param status
     * @param pageNo
     * @param pageSize
     * @param type
     * @return
     */
    public ServerResponse listForPlatform(Short status, int pageNo, int pageSize, String keyword, String type) {
        Page<Demand> page = new Page<>(pageNo, pageSize);
        List<Demand> records = demandMapper.selectByPage(page, null, null, status, keyword, type);
        if (!records.isEmpty()) {
            for (Demand demand : records) {
                if (demand.getShopId() != null) {
                    demand.setShopName(shopMapper.selectByPrimaryKey(demand.getShopId()).getName());
                }
                OrderStatus orderStatus = orderStatusMapper.selectByStatus(demand.getStatus());
                demand.setStatusDtl(orderStatus);
            }
        }
        page.setRecords(records);
        return ServerResponse.createBySuccess(page);
    }

    /**
     * 客户订单结算
     *
     * @param status
     * @param pageNo
     * @param pageSize
     * @param type
     * @return
     */
    public ServerResponse listForPlatformBalance(Short status, int pageNo, int pageSize, String keyword, String type) {
        Page<Demand> page = new Page<>(pageNo, pageSize);
        List<Demand> records = demandMapper.selectByPage(page, null, null, status, keyword, type);
        if (!records.isEmpty()) {
            for (Demand demand : records) {
                if (demand.getShopId() != null) {
                    demand.setShopName(shopMapper.selectByPrimaryKey(demand.getShopId()).getName());
                }
                OrderStatus orderStatus = orderStatusMapper.selectByStatus(demand.getStatus());
                demand.setStatusDtl(orderStatus);
                //计算支付明细
                List<DemandCustomerPayFlow> demandCustomerPayFlows = demandCustomerPayFlowMapper.selectbyDemandId(demand.getId());
                //计算待支付
                if (demand.getPayStatus() < 2) {
                    DemandCustomerPayFlow remain = new DemandCustomerPayFlow();
                    remain.setAccount("---");
                    remain.setMoney(demand.getWaittingPay());
                    demandCustomerPayFlows.add(remain);
                }
                demand.setCustomerPayFlow(demandCustomerPayFlows);
                //计算商家结算明细
                List<DemandShopPayFlow> demandShopPayFlows = demandShopPayFlowMapper.selectbyDemandId(demand.getId());
                demand.setShopPayFlow(demandShopPayFlows);
            }
        }
        page.setRecords(records);
        return ServerResponse.createBySuccess(page);
    }


    /**
     * @param pageNo
     * @param pageSize
     * @return
     */
    public ServerResponse listForCustomer(Short status, int pageNo, int pageSize, String keyword, String type) {
        WUser user = UserContext.getUser();
        Page<Demand> page = new Page<>(pageNo, pageSize);
        page.setRecords(demandMapper.selectByPage(page, user.getId(), null, status, keyword, type));
        return ServerResponse.createBySuccess(page);
    }

    /**
     * 业务员添加
     *
     * @param dto
     * @return
     */
    @Transactional
    public ServerResponse addDemandItem(DemandItemDto dto) {
        if (dto == null) {
            return ServerResponse.createByErrorMessage("请提交客户需求信息");
        }
        if (dto.getItem() == null) {
            return ServerResponse.createByErrorMessage("请提交客户需求详情");
        }

        DemandItem item = dto.getItem();
        if (item.getId() == null) {
            itemMapper.insertSelective(item);
            if (dto.getPics() != null) {
                for (DemandItemMedia itemMedia : dto.getPics()) {
                    itemMedia.setDemandItemId(item.getId());
                    itemMedia.setType(0);
                    mediaMapper.insertSelective(itemMedia);
                }
            }
            if (dto.getVideo() != null) {
                DemandItemMedia video = dto.getVideo();
                video.setDemandItemId(item.getId());
                video.setType(1);
                mediaMapper.insertSelective(video);
            }
        } else {
            itemMapper.updateByPrimaryKeySelective(item);
            if (dto.getPics() != null) {
                for (DemandItemMedia itemMedia : dto.getPics()) {
                    itemMedia.setDemandItemId(item.getId());
                    itemMedia.setType(0);
                    mediaMapper.updateByPrimaryKeySelective(itemMedia);
                }
            }
            if (dto.getVideo() != null) {
                DemandItemMedia video = dto.getVideo();
                video.setDemandItemId(item.getId());
                video.setType(1);
                mediaMapper.updateByPrimaryKeySelective(video);
            }
        }

        return ServerResponse.createByErrorMessage("操作成功!");
    }


    /**
     * 更新订单状态
     *
     * @param demandStatus
     * @return
     */
    public ServerResponse updateOrderStatus(DemandStatusDto demandStatus) {
        if (demandStatus == null) {
            return ServerResponse.createByErrorMessage("请提交状态信息!");
        }

        if (demandStatus.getDemandId() == null) {
            return ServerResponse.createByErrorMessage("请提交 demandId!");
        }

        if (demandStatus.getStatus() == null) {
            return ServerResponse.createByErrorMessage("请提交status!");
        }

        //判断用户是否有权限
        Demand demand = demandMapper.selectByPrimaryKey(demandStatus.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单不存在,请核实!");
        }

        Demand record = new Demand();
        record.setId(demandStatus.getDemandId());
        demandMapper.updateByPrimaryKeySelective(record);

        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    /**
     * 获取需求详情
     *
     * @param id
     * @return
     */
    public ServerResponse item(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("请提交订单ID!");
        }
        Demand demand = demandMapper.selectByPrimaryKey(id);
        if (demand == null) {
            return ServerResponse.createByErrorMessage("该笔订单不存在,请核实!!");
        }
        DemandDto demandDto = new DemandDto();
        if (demand.getShopId() != null) {
            WShop wShop = shopMapper.selectByPrimaryKey(demand.getShopId());
            demandDto.setShop(wShop);
        }

        demandDto.setDemand(demand);
        demandDto.setOperateLogs(demandOperateLogMapper.selectByDemandId(demand.getId()));
        if (demand.getPicUrls() != null) {
            demandDto.setDemandUrls(demand.getPicUrls().split(","));
        }

        List<DemandItem> items = itemMapper.selectByDemandId(id);
        DemandItemDto itemDto = null;
        List<DemandItemDto> demandItemDtos = new ArrayList<>();
        for (DemandItem item : items) {
            itemDto = new DemandItemDto();
            itemDto.setItem(item);
            List<DemandItemMedia> pics = mediaMapper.selectByItemId(item.getId(), 0);
            itemDto.setPics(pics);
            List<DemandItemMedia> video = mediaMapper.selectByItemId(item.getId(), 1);
            if (video != null && !video.isEmpty()) {
                itemDto.setVideo(video.get(video.size() - 1));
            }
            demandItemDtos.add(itemDto);
        }

        if (!demandItemDtos.isEmpty()) {
            demandDto.setItem(demandItemDtos.get(0).getItem());
            List<OrderStatus> orderStatuses = orderStatusMapper.selectAll();
            demandDto.setOrderStatuses(orderStatuses);
            DemandItem item = items.get(0);
            List<DemandArrival> arrivalInfos = arrivalMapper.selectByItemId(item.getId(), null);
            if (arrivalInfos != null && !arrivalInfos.isEmpty()) {
                demandDto.setAppointArrivalList(arrivalInfos);
            }

            //工程方案
            DemandProject project = projectMapper.selectByItemId(item.getId());
            if (project != null) {
                DemandProjectOutDto demandProjectOutDto = new DemandProjectOutDto();
                BeanUtils.copyProperties(project, demandProjectOutDto);
                demandDto.setProject(demandProjectOutDto);
            }

            //施工方案图
            List<DemandItemMedia> projectPlan = mediaMapper.selectByItemId(item.getId(), 2);
            demandDto.setProjectPlanPicsUrls(projectPlan);

            // 施工完成图
            List<DemandItemMedia> setPicUrls = mediaMapper.selectByItemId(item.getId(), 3);
            demandDto.setProjectDonePicUrls(setPicUrls);

            //用户评论
            DemandComment comment = demandCommentMapper.selectByItemId(demand.getId());
            List<DemandItemMedia> commentPicUrls = mediaMapper.selectByItemId(item.getId(), 4);
            if (comment != null) {
                DemandCommentOutDto commentDto = new DemandCommentOutDto();
                BeanUtils.copyProperties(comment, commentDto);
                commentDto.setPicUrls(commentPicUrls);
                demandDto.setComment(commentDto);
            }

            //talks
            List<DemandTalk> talks = talkMapper.selectByDemandId(demand.getId());
            demandDto.setTalks(talks);
        }

        return ServerResponse.createBySuccess("订单详情查询成功!", demandDto);
    }


    /**
     * 分配店铺
     *
     * @param dispatchParam
     * @return
     */
    public ServerResponse dispatchShop(DispatchParam dispatchParam) {
        WShop shop = shopMapper.selectByPrimaryKey(dispatchParam.getShopId());
        if (shop == null) {
            return ServerResponse.createByErrorMessage("店铺不存在,请核实!");
        }

        Demand demand = demandMapper.selectByPrimaryKey(dispatchParam.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单不存在,请核实!");
        }
        WUser user = UserContext.getUser();
        String content = null;
        if (demand.getShopId() == null) {
            content = "平台人员【" + user.getName() + "】分配订单至店铺【" + shop.getName() + "】";
        } else {
            content = "平台人员【" + user.getName() + "】重新分配订单至店铺【" + shop.getName() + "】";
        }

        demand.setDispatchUid(user.getId());
        demand.setShopId(dispatchParam.getShopId());
        demand.setStatus((short) 1);
        demandMapper.updateByPrimaryKeySelective(demand);
        //更新demandItem的shopId
        itemMapper.updateShopIdByDemandId(demand.getId(), demand.getShopId());

        insertOperateLog(demand.getId(), user.getId(), content);
        DispatchParam sale = new DispatchParam();
        sale.setDemandId(demand.getId());
        sale.setOperateUid(user.getId());
        dispatchSalesman(sale);

        return ServerResponse.createBySuccessMessage("店铺分配完成!");
    }

    /**
     * 分配业务员上门
     *
     * @param dispatchParam
     * @return
     */
    public ServerResponse dispatchSalesman(DispatchParam dispatchParam) {
        Demand demand = demandMapper.selectByPrimaryKey(dispatchParam.getDemandId());
        if (demand.getShopId() == null) {
            return ServerResponse.createByErrorMessage("订单尚未分配店铺,请分配店铺后再分配业务员!");
        }
        WUser user = UserContext.getUser();
        String content = null;
        Integer operateUid = dispatchParam.getOperateUid();
        WUser dispatchUser = userMapper.selectByPrimaryKey(operateUid);
        if (demand.getOperateUid() == null) {
            content = "【" + user.getName() + "】分配业务员【" + dispatchUser.getName() + "】跟单!";
        } else {
            content = "【" + user.getName() + "】重新分配业务员【" + dispatchUser.getName() + "】跟单!";
        }

        demand.setOperateUid(dispatchParam.getOperateUid());
        demandMapper.updateByPrimaryKeySelective(demand);

        insertOperateLog(demand.getId(), user.getId(), content);
        return ServerResponse.createBySuccessMessage("人员分配完成!");
    }

    /**
     * 设置预约时间
     *
     * @param appointParam
     * @return
     */
    @Transactional
    public ServerResponse setTime(AppointParam appointParam) {
        if (appointParam == null) {
            return ServerResponse.createByErrorMessage("预约时间参数设置不合法!");
        }

        if (appointParam.getDemandId() == null) {
            return ServerResponse.createByErrorMessage("请提交订单id!");
        }
        if (appointParam.getTime() == null) {
            return ServerResponse.createByErrorMessage("请设置上门时间!");
        }
        Instant inst1 = Instant.now();
        boolean before = inst1.isBefore(appointParam.getTime().toInstant());
        if (!before) {
            return ServerResponse.createByErrorMessage("上门时间设置有误!");
        }
        Demand demand = demandMapper.selectByPrimaryKey(appointParam.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("该订单已被删除,请核实!");
        }

        WUser user = UserContext.getUser();

        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem item = demandItems.get(demandItems.size() - 1);
        String appointTime = DateTimeUtil.dateToStr(appointParam.getTime());
        //插入预约时间,更新
        List<DemandArrival> demandArrivals = arrivalMapper.selectByItemId(item.getId(), 0);
        Integer arrivalId = null;
        if (!demandArrivals.isEmpty()) {
            DemandArrival arrival = demandArrivals.get(demandArrivals.size() - 1);
            arrivalId = arrival.getId();
            arrival.setItemId(item.getId());
            arrival.setLastUpdateTime(appointParam.getTime());
            arrivalMapper.updateByPrimaryKeySelective(arrival);
            //保存日志
            log.info("======已修改与客户预约时间========");
            insertOperateLog(demand.getId(), user.getId(), "【" + user.getName() + "】已修改与客户预约时间为:" + appointTime);
            //查询消息
            String scheduleId = arrival.getScheduleId();
            //取消之前的推送
            pushService.cancleScheduleUser(scheduleId);

        } else {
            //   绑定店铺与客户
            ShopUserRelation shopUserRelation = new ShopUserRelation();
            shopUserRelation.setName(demand.getName());
            shopUserRelation.setOperateUid(demand.getOperateUid());
            shopUserRelation.setPhone(demand.getPhone());
            shopUserRelation.setShopId(demand.getShopId());
            shopUserRelation.setUserId(demand.getUserId());
            shopUserRelation.setDtlAddress(demand.getDtladdress());
            shopUserRelationMapper.insertSelective(shopUserRelation);

            DemandArrival arrival = new DemandArrival();
            arrival.setLastUpdateTime(appointParam.getTime());
            arrival.setItemId(item.getId());
            arrivalMapper.insertSelective(arrival);
            arrivalId = arrival.getId();
            //保存日志
            log.info("======已经与客户预约========");
            insertOperateLog(demand.getId(), user.getId(), "【" + user.getName() + "】已与客户预约时间为:" + appointTime);
        }


        //定时推送
        log.info("======push========");
        String nitice = "【" + user.getName() + "】已与您预约上门时间为:" + appointTime;
        ServerResponse<String> scheduleResp = pushService.scheduleUser(nitice, "预约上门", appointTime);
        if (scheduleResp.isSuccess()) {
            String scheduleId = scheduleResp.getData();
            //插入消息
            Message message = new Message();
            Integer shopId = user.getShopInfo().getId();

            WShop wShop = shopMapper.selectByPrimaryKey(shopId);
            String content = "您好,商家【" + wShop.getName() + "】将于:<font color='#ff6f00'>" + appointTime + "</font>上门为您服务。";
            message.setContent(content);
            message.setUid(demand.getUserId());
            message.setHandleUid(user.getId());
            message.setScheduleId(scheduleId);
            message.setType(0);

            message.setShopPhone(user.getPhone());
            message.setShopId(demand.getShopId());
            messageService.addOrUpdate(message);
            //更新arrivalId
            DemandArrival arrival = new DemandArrival();
            arrival.setId(arrivalId);
            arrival.setScheduleId(scheduleId);
            arrivalMapper.updateByPrimaryKeySelective(arrival);
        }

        demand.setStatus((short) 2);
        demandMapper.updateByPrimaryKeySelective(demand);
        return ServerResponse.createBySuccessMessage("预约时间设置成功");
    }


    /**
     * 确认到达
     *
     * @return
     */
    @Transactional
    public ServerResponse confirmArrival(ConfirmArrivalInfo arrivalInfo) {
        if (arrivalInfo == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }

        if (arrivalInfo.getDemandId() == null) {
            return ServerResponse.createByErrorMessage("请提交订单itemId!");
        }


        //修改订单状态
        List<DemandItem> items = itemMapper.selectByDemandId(arrivalInfo.getDemandId());
        DemandItem item = items.get(items.size() - 1);
        Integer demandId = item.getDemandId();

        //最后一条待处理上门计划
        List<DemandArrival> demandArrivas = arrivalMapper.selectByItemId(item.getId(), 0);
        if (demandArrivas.isEmpty()) {
            return ServerResponse.createBySuccessMessage("状态异常,无法确认到达!");
        }
        DemandArrival demandArrival = demandArrivas.get(demandArrivas.size() - 1);
        demandArrival.setStatus(1);
        demandArrival.setPicUrl(arrivalInfo.getPicUrl());
        arrivalMapper.updateByPrimaryKeySelective(demandArrival);


        //修改订单状态
        Demand record = new Demand();
        record.setId(demandId);
        record.setStatus((short) 3);
        demandMapper.updateByPrimaryKeySelective(record);
        WUser user = UserContext.getUser();
        insertOperateLog(record.getId(), user.getId(), "【" + user.getName() + "】已经确认到达!");

        return ServerResponse.createBySuccessMessage("已经确认到达!");
    }

    /**
     * 创建施工方案
     *
     * @return
     */
    @Transactional
    public ServerResponse createProject(DemandProjectDto projectDto) {
        if (projectDto == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }
        if (projectDto.getTotalPrice() == null) {
            return ServerResponse.createByErrorMessage("请设置订单金额!");
        }

        if (projectDto.getPrice() == null) {
            projectDto.setPrice(new BigDecimal(0));
        }


        DemandProject demandProject = new DemandProject();
        demandProject.setEffect(0);
        BeanUtils.copyProperties(projectDto, demandProject);
        //特殊处理itemId
        Demand demand = demandMapper.selectByPrimaryKey(projectDto.getDemandId());
        demand.setWaittingPayForShop(projectDto.getTotalPrice());
        demand.setTotalPrice(projectDto.getTotalPrice());
        demand.setWaittingPay(projectDto.getTotalPrice());
        demand.setPaid(new BigDecimal(0));
        demandMapper.updateByPrimaryKeySelective(demand);


        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem demandItem = demandItems.get(demandItems.size() - 1);
        demandProject.setItemId(demandItem.getId());
        projectMapper.insertSelective(demandProject);
        List<String> picUrls = projectDto.getPicUrls();
        for (int i = 0; picUrls != null && i < picUrls.size(); i++) {
            String picItem = picUrls.get(i);
            if (StringUtils.isEmpty(picItem)) {
                continue;
            }
            DemandItemMedia rc = new DemandItemMedia();
            rc.setType(2);
            rc.setDemandItemId(demandProject.getItemId());
            rc.setResource(picItem);
            mediaMapper.insertSelective(rc);
        }

        //修改订单状态
        DemandItem item = itemMapper.selectByPrimaryKey(demandProject.getItemId());
        Integer demandId = item.getDemandId();
        Demand record = new Demand();
        record.setId(demandId);
        record.setStatus((short) 4);
        demandMapper.updateByPrimaryKeySelective(record);
        WUser user = UserContext.getUser();
        insertOperateLog(record.getId(), user.getId(), "【" + user.getName() + "】已经提交施工方案!");

        return ServerResponse.createBySuccessMessage("方案图提交成功!");
    }


    public ServerResponse confirmProjectAndPay(Integer demandId) {
        if (demandId == null) {
            return ServerResponse.createByErrorMessage("请提交demandId!");
        }
        Demand demand = demandMapper.selectByPrimaryKey(demandId);
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单已被删除,请核实!");
        }
        //查询定金金额
        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem demandItem = demandItems.get(demandItems.size() - 1);
        DemandProject demandProject = projectMapper.selectByItemId(demandItem.getId());


        EBRequestParam payParam = new EBRequestParam();
        String s = DateTimeUtil.dateToStr(new Date(), DateTimeUtil.STANDARD_FORMAT1);
        payParam.setRequestid(s);
        payParam.setAmount(demandProject.getPrice() + "");
        payParam.setDirectcode("WAP-ZHT");
        payParam.setPayproducttype("ONEKEY");
        payParam.setCallbackurl(Const.CREATEPROJECTCALLBACK);
        payParam.setUserno(demand.getUserId().toString());
        String proName = "窗e生平台订单";
        if (!StringUtils.isEmpty(demand.getDemand()) && demand.getDemand().length() > 49) {
            proName = demand.getDemand().substring(0, 48);
        }

        payParam.setProductname(proName);
        ServerResponse<EBPayRespDTO> pay = payService.pay(payParam);
        if (!pay.isSuccess()) {
            return pay;
        }
        EBPayRespDTO data = pay.getData();
        demand.setEbExternalId(data.getExternalid());
        demandMapper.updateByPrimaryKeySelective(demand);
        return ServerResponse.createBySuccess(data.getPayurl());
    }


    /**
     * 方案确认支付定金
     */
    @Transactional
    public ServerResponse confirmProjectAndPayCallback(EBPayRespDTO ebPayRespDTO) {
        DemandCustomerPayFlow flow = demandCustomerPayFlowMapper.selectByEBExternalId(ebPayRespDTO.getExternalid());
        if (flow != null) {
            log.info("重复确认回调通知信息:" + ebPayRespDTO);
            return ServerResponse.createBySuccessMessage("方案确认已支付定金!");
        }

        //修改订单状态
        Demand record = demandMapper.selectByEbExternalId(ebPayRespDTO.getExternalid());
        record.setStatus((short) 5);
        //更新金额
        record.setWaittingPay(record.getTotalPrice().min(ebPayRespDTO.getAmount()));
        record.setPaid(ebPayRespDTO.getAmount());

        demandMapper.updateByPrimaryKeySelective(record);
        List<DemandItem> demandItems = itemMapper.selectByDemandId(record.getId());
        DemandItem demandItem = demandItems.get(demandItems.size() - 1);
        DemandProject demandProject = projectMapper.selectByItemId(demandItem.getId());

        //插入流水记录
        DemandCustomerPayFlow payFlow = new DemandCustomerPayFlow();
        payFlow.setAccount(ebPayRespDTO.getCardno());
        payFlow.setMoney(demandProject.getPrice());
        payFlow.setDemandId(record.getId());
        payFlow.setItemId(demandItem.getId());
        payFlow.setShopId(record.getShopId());
        payFlow.setEbExternalId(ebPayRespDTO.getExternalid());
        if (demandProject.getPayType().equals(0)) {
            payFlow.setTitle("全额");
        } else {
            payFlow.setTitle("定金");
        }
        demandCustomerPayFlowMapper.insertSelective(payFlow);
        producing(record.getId(), 0);
        return ServerResponse.createBySuccessMessage("方案确认已支付定金!");
    }

    /**
     * 生产中
     */
    @Transactional
    public ServerResponse producing(Integer demandId, Integer producingStep) {
        //修改订单状态
        Demand record = new Demand();
        record.setId(demandId);
        record.setStatus((short) 6);
        record.setProducingStep(producingStep);
        demandMapper.updateByPrimaryKeySelective(record);
        WUser user = UserContext.getUser();
        insertOperateLog(record.getId(), user.getId(), "订单正在生产中");

        return ServerResponse.createBySuccessMessage("正在生产中!");
    }

    /**
     * 7. 生产完成
     */
    @Transactional
    public ServerResponse produceDone(Integer demandId) {
        Demand record = new Demand();
        record.setId(demandId);
        record.setStatus((short) 7);
        demandMapper.updateByPrimaryKeySelective(record);
        WUser user = UserContext.getUser();
        insertOperateLog(record.getId(), user.getId(), "订单生产完成!");
        return ServerResponse.createBySuccessMessage("生产完成!");
    }

    /**
     * 8.预约施工
     */
    @Transactional
    public ServerResponse appointInstall(AppointParam appointParam) {
        if (appointParam == null) {
            return ServerResponse.createByErrorMessage("预约时间参数设置不合法!");
        }

        if (appointParam.getDemandId() == null) {
            return ServerResponse.createByErrorMessage("请提交订单id!");
        }
        if (appointParam.getTime() == null) {
            return ServerResponse.createByErrorMessage("请设置上门时间!");
        }

        Instant inst1 = Instant.now();
        boolean before = inst1.isBefore(appointParam.getTime().toInstant());
        if (!before) {
            return ServerResponse.createByErrorMessage("上门时间设置有误!");
        }


        Demand demand = demandMapper.selectByPrimaryKey(appointParam.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("该订单已被删除,请核实!");
        }

        String appointTime = DateTimeUtil.dateToStr(appointParam.getTime());
        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem record = demandItems.get(0);

        WUser user = UserContext.getUser();
        //插入预约时间,更新
        List<DemandArrival> demandArrivals = arrivalMapper.selectByItemId(record.getId(), 1);
        Integer arrivalId = null;
        if (!demandArrivals.isEmpty()) {
            DemandArrival arrival = demandArrivals.get(demandArrivals.size() - 1);
            arrivalId = arrival.getId();
            arrival.setItemId(record.getId());
            arrival.setLastUpdateTime(appointParam.getTime());
            arrivalMapper.updateByPrimaryKeySelective(arrival);
            //保存日志
            log.info("======已修改与客户预约时间========");
            insertOperateLog(demand.getId(), user.getId(), "【" + user.getName() + "】已修改与客户预约时间为:" + appointTime);
            //查询消息
            String scheduleId = arrival.getScheduleId();
            //取消之前的推送
            pushService.cancleScheduleUser(scheduleId);

        } else {

            DemandArrival arrival = new DemandArrival();
            arrival.setArrivalType(1);
            arrival.setLastUpdateTime(appointParam.getTime());
            arrival.setItemId(record.getId());
            arrivalMapper.insertSelective(arrival);
            arrivalId = arrival.getId();
            //保存日志
            log.info("======已经与客户预约========");
            insertOperateLog(demand.getId(), user.getId(), "【" + user.getName() + "】已与客户预约时间为:" + appointTime);
        }


        //定时推送
        log.info("======push========");
        String nitice = "【" + user.getName() + "】已与您预约上门时间为:" + appointTime;
        ServerResponse<String> scheduleResp = pushService.scheduleUser(nitice, "预约上门", appointTime);
        if (scheduleResp.isSuccess()) {
            String scheduleId = scheduleResp.getData();
            //插入消息
            Message message = new Message();
            Integer shopId = user.getShopInfo().getId();

            WShop wShop = shopMapper.selectByPrimaryKey(shopId);
            String content = "您好,商家【" + wShop.getName() + "】将于:<font color='#ff6f00'>" + appointTime + "</font>上门为您服务。";
            message.setContent(content);
            message.setUid(demand.getUserId());
            message.setHandleUid(user.getId());
            message.setScheduleId(scheduleId);
            message.setType(0);

            message.setShopPhone(user.getPhone());
            message.setShopId(demand.getShopId());
            messageService.addOrUpdate(message);
            //更新arrivalId
            DemandArrival arrival = new DemandArrival();
            arrival.setId(arrivalId);
            arrival.setScheduleId(scheduleId);
            arrivalMapper.updateByPrimaryKeySelective(arrival);
        }

        demand.setStatus((short) 8);
        demandMapper.updateByPrimaryKeySelective(demand);
        return ServerResponse.createBySuccessMessage("预约时间设置成功");
    }


    /**
     * 确认到达
     *
     * @return
     */
    public ServerResponse confirmInstallArrival(ConfirmArrivalInfo arrivalInfo) {
        if (arrivalInfo == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }

        if (arrivalInfo.getDemandId() == null) {
            return ServerResponse.createByErrorMessage("请提交订单itemId!");
        }


        Demand demand = demandMapper.selectByPrimaryKey(arrivalInfo.getDemandId());
        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem item = demandItems.get(0);
        DemandArrival demandArrival = arrivalMapper.selectByPrimaryKey(item.getId());

        demandArrival.setStatus(1);
        demandArrival.setPicUrl(arrivalInfo.getPicUrl());

        //修改订单状态
        Demand record = new Demand();
        record.setId(arrivalInfo.getDemandId());
        record.setStatus((short) 9);
        demandMapper.updateByPrimaryKeySelective(record);

        WUser user = UserContext.getUser();
        insertOperateLog(record.getId(), user.getId(), "已经确认到达!");

        return ServerResponse.createBySuccessMessage("已经确认到达!");
    }

    /**
     * 客户支付全款 10
     *
     * @param payInfo
     * @return
     */
    public ServerResponse completeAll(PayInfo payInfo) {
        //修改订单状态
        Demand demand = demandMapper.selectByPrimaryKey(payInfo.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单已被删除,请核实!");
        }

        //如果 待支付金额0
        if (demand.getWaittingPay().compareTo(new BigDecimal(0.0)) == 0) {
            demand.setPaid(demand.getTotalPrice().min(demand.getWaittingPay()));
            demand.setStatus((short) 11);
            demandMapper.updateByPrimaryKeySelective(demand);
            WUser user = userMapper.selectByPrimaryKey(demand.getUserId());
            insertOperateLog(demand.getId(), user.getId(), "尾款已结清");
            return ServerResponse.createBySuccessMessage("尾款已结清!");
        }

        EBRequestParam payParam = new EBRequestParam();
        String s = demand.getEbExternalId() + "|" + demand.getId();
        payParam.setRequestid(s);
        payParam.setAmount(demand.getWaittingPay() + "");
        payParam.setDirectcode("WAP-ZHT");
        payParam.setPayproducttype("ONEKEY");
        payParam.setCallbackurl(Const.COMPLETEALLCALLBACK);
        payParam.setUserno(demand.getUserId().toString());
        String proName = "窗e生平台订单";
        if (!StringUtils.isEmpty(demand.getDemand()) && demand.getDemand().length() > 49) {
            proName = demand.getDemand().substring(0, 48);
        }

        payParam.setProductname(proName);
        ServerResponse<EBPayRespDTO> pay = payService.pay(payParam);
        if (!pay.isSuccess()) {
            return pay;
        }
        EBPayRespDTO data = pay.getData();
        demand.setEbExternalId(data.getExternalid());
        demandMapper.updateByPrimaryKeySelective(demand);
        return ServerResponse.createBySuccess(data.getPayurl());
    }

    /**
     * 客户支付全款 10
     *
     * @return
     */
    @Transactional
    public ServerResponse completeAllCallback(EBPayRespDTO ebPayRespDTO) {
        //修改订单状态
        String requestid = ebPayRespDTO.getRequestid();
        String[] split = requestid.split("\\|");
        String demandIdStr = split[1];
        Demand record = demandMapper.selectByPrimaryKey(new Integer(demandIdStr));
        record.setStatus((short) 11);
        //更新金额
        record.setWaittingPay(record.getWaittingPay().min(ebPayRespDTO.getAmount()));
        record.setPaid(record.getTotalPrice().min(record.getWaittingPay()));

        demandMapper.updateByPrimaryKeySelective(record);
        List<DemandItem> demandItems = itemMapper.selectByDemandId(record.getId());
        DemandItem demandItem = demandItems.get(demandItems.size() - 1);
        DemandProject demandProject = projectMapper.selectByItemId(demandItem.getId());

        //插入流水记录
        DemandCustomerPayFlow payFlow = new DemandCustomerPayFlow();
        payFlow.setAccount(ebPayRespDTO.getCardno());
        payFlow.setMoney(demandProject.getPrice());
        payFlow.setDemandId(record.getId());
        payFlow.setItemId(demandItem.getId());
        payFlow.setShopId(record.getShopId());
        payFlow.setEbExternalId(ebPayRespDTO.getExternalid());
        if (demandProject.getPayType().equals(0)) {
            payFlow.setTitle("全额");
        } else {
            payFlow.setTitle("定金");
        }
        demandCustomerPayFlowMapper.insertSelective(payFlow);

        //修改订单状态
        demandMapper.updateByPrimaryKeySelective(record);
        WUser user = userMapper.selectByPrimaryKey(record.getUserId());
        insertOperateLog(record.getId(), user.getId(), "尾款已结清");
        return ServerResponse.createBySuccessMessage("尾款已结清!");
    }


    /**
     * 上传施工图片
     */
    @Transactional
    public ServerResponse addInstallCases(ProjectDoneDto projectDto) {
        if (projectDto == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }

        //创建方案
        DemandProjectDto plan = projectDto.getPlan();
        if (plan != null) {
            //开始赋值操作
            plan.setProjectType(0);
            plan.setPrice(new BigDecimal(0.0));
            if (plan.getPrice() == null) {
                plan.setTotalPrice(new BigDecimal(0.0));
            }
            plan.setDemandId(projectDto.getDemandId());
            createProject(plan);
        }


        Demand demand = demandMapper.selectByPrimaryKey(projectDto.getDemandId());
        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem item = demandItems.get(0);


        List<String> picUrls = projectDto.getPicUrls();
        for (int i = 0; picUrls != null && i < picUrls.size(); i++) {
            String picItem = picUrls.get(i);
            if (StringUtils.isEmpty(picItem)) {
                continue;
            }
            DemandItemMedia rc = new DemandItemMedia();
            rc.setType(3);
            rc.setDemandItemId(item.getId());
            rc.setResource(picItem);
            mediaMapper.insertSelective(rc);
        }

        Integer demandId = item.getDemandId();
        Demand record = new Demand();
        record.setId(demandId);
        record.setStatus((short) 11);
        demandMapper.updateByPrimaryKeySelective(record);

        WUser user = UserContext.getUser();
        insertOperateLog(record.getId(), user.getId(), "施工图提交成功");
        return ServerResponse.createBySuccessMessage("施工图提交成功!");
    }


    /**
     * @param commentDto
     * @return
     */
    @Transactional
    public ServerResponse doComment(DemandCommentDto commentDto) {
        if (commentDto == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }

        Integer demandId = commentDto.getDemandId();
        Demand demand = demandMapper.selectByPrimaryKey(demandId);


        List<DemandItem> demandItems = itemMapper.selectByDemandId(demandId);
        DemandItem item = demandItems.get(0);


        DemandComment comment = new DemandComment();
        comment.setShopId(demand.getShopId());
        BeanUtils.copyProperties(commentDto, comment);
        demandCommentMapper.insertSelective(comment);

        if (commentDto.getPicUrls() != null) {
            for (String pic : commentDto.getPicUrls()) {
                DemandItemMedia itemMedia = new DemandItemMedia();
                itemMedia.setResource(pic);
                itemMedia.setDemandItemId(item.getId());
                itemMedia.setType(4);
                mediaMapper.insertSelective(itemMedia);
            }
        }

        Demand record = new Demand();
        record.setId(demandId);
        record.setStatus((short) 12);
        demandMapper.updateByPrimaryKeySelective(record);


        WUser user = UserContext.getUser();

        //添加留言信息
        DemandTalk talk = new DemandTalk();
        talk.setDemandId(demandId);
        talk.setShopId(demand.getShopId());
        talk.setContent(commentDto.getRemark());
        talk.setType(2);
        talk.setUid(user.getId());
        talkMapper.insertSelective(talk);

        insertOperateLog(record.getId(), user.getId(), "已评价!");
        return ServerResponse.createBySuccessMessage("评价成功，谢谢你的支持!");
    }


    /**
     * 补全用户信息
     *
     * @param demandUserInfo
     * @return
     */
    @Transactional
    public ServerResponse updateCustomerInfo(DemandUserInfo demandUserInfo) {
        if (demandUserInfo == null) {
            return ServerResponse.createByErrorMessage("请提交用户信息!");
        }

        String area = demandUserInfo.getArea();
        Integer categroryId = demandUserInfo.getCategoryId();
        Short intentLevel = demandUserInfo.getIntentLevel();
        Integer lifeLevel = demandUserInfo.getLifeLevel();
        Integer shapeId = demandUserInfo.getShapeId();

        String category = demandUserInfo.getCategory();
        String shape = demandUserInfo.getShape();
        String intent = demandUserInfo.getIntent();

        String year = demandUserInfo.getYear();
        Integer demandId = demandUserInfo.getDemandId();

        //更新需求
        Demand demand = demandMapper.selectByPrimaryKey(demandId);
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单已被删除,请核实!");
        }


        demand.setIntent(intent);
        demand.setShape(shape);
        demand.setCategory(category);
        demand.setArea(area);

        demand.setIntentLevel(intentLevel);
        demandMapper.updateByPrimaryKeySelective(demand);
        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        if (demandItems.isEmpty()) {
            DemandItem item = new DemandItem();
            item.setDemandId(demand.getId());
            item.setCategroryId(categroryId);
            item.setShapeId(shapeId);
            item.setYear(year);
            itemMapper.insertSelective(item);
        } else {
            DemandItem item = demandItems.get(0);
            item.setCategroryId(categroryId);
            item.setShapeId(shapeId);
            item.setYear(year);
            itemMapper.updateByPrimaryKeySelective(item);
        }


        //更新用户信息
        Integer userId = demand.getUserId();
        WUser wUser = userMapper.selectByPrimaryKey(userId);
        wUser.setLifeLevel(lifeLevel);
        wUser.setLife(demandUserInfo.getLife());
        userMapper.updateByPrimaryKeySelective(wUser);

        return ServerResponse.createBySuccessMessage("更新成功!");
    }

    /**
     * @param id 店铺
     * @return
     */
    public ServerResponse listDemandByShopId(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }
        List<Integer> ids = new ArrayList<>();
        ids.add(id);
        List<Demand> demands = demandMapper.selectAllByShopIds(ids);
        if (demands != null && !demands.isEmpty()) {
            return ServerResponse.createBySuccess("查询成功!", demands);
        }
        return ServerResponse.createByErrorMessage("查询失败!");
    }


    /**
     * @param id 店铺
     * @return
     */
    public ServerResponse listDemandByUserId(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("参数提交不合法!");
        }
        Integer sId = UserContext.getUser().getSId();
        List<Demand> demands = demandMapper.selectDemads(id, sId);
        if (demands != null && !demands.isEmpty()) {
            return ServerResponse.createBySuccess("查询成功!", demands);
        }
        return ServerResponse.createByErrorMessage("查询失败!");
    }


    /**
     * 取消订单
     *
     * @param cancleDTO
     * @return
     */
    @Transactional
    public ServerResponse cancle(CancleDTO cancleDTO) {
        if (cancleDTO.getDemandId() == null) {
            return ServerResponse.createByErrorMessage("请提交demandId!");
        }
        Integer demandId = cancleDTO.getDemandId();
        Demand demand = demandMapper.selectByPrimaryKey(demandId);
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单不存在,请核实!");
        }

        WUser user = UserContext.getUser();
        if (demand.getUserId().equals(user.getId())) {
            return ServerResponse.createByErrorMessage("权限不足,无法操作该订单!");
        }

        if (demand.getStatus().intValue() >= 2) {
            return ServerResponse.createByErrorMessage("该订单已在进行中,无法取消!");
        }

        List<DemandItem> demandItems = itemMapper.selectByDemandId(demand.getId());
        DemandItem item = demandItems.get(demandItems.size() - 1);
        //插入预约时间,更新
        List<DemandArrival> demandArrivals = arrivalMapper.selectByItemId(item.getId(), null);
        if (!demandArrivals.isEmpty()) {
            return ServerResponse.createByErrorMessage("该订单已在进行中,无法取消!");
        }

        insertOperateLog(demandId, user.getId(), "用户【" + user.getName() + "】取消订单!备注:" + cancleDTO.getRemark());
        demand.setShopId(null);
        demand.setOperateUid(null);
        demand.setStatus((short) 0);
        demandMapper.updateByPrimaryKey(demand);

        //开始记录取消日志
        DemandCancleLog log = new DemandCancleLog();
        log.setContent("用户主动取消订单");
        log.setDemandId(demand.getId());
        log.setShopId(demand.getShopId());
        log.setType(0);
        log.setUserId(demand.getUserId());
        demandCancleLogMapper.insertSelective(log);


        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    /**
     * 取消订单
     *
     * @param cancleDTO
     * @return
     */
    @Transactional
    public ServerResponse cancleForShop(CancleDTO cancleDTO) {
        Demand demand = demandMapper.selectByPrimaryKey(cancleDTO.getDemandId());
        if (demand.getStatus().intValue() >= 5) {
            return ServerResponse.createByErrorMessage("该订单已在进行中,无法取消!");
        }

        WUser user = UserContext.getUser();
        Integer sId = user.getSId();
        WShop wShop = shopMapper.selectByPrimaryKey(sId);
        //开始扣除服务分
        Sys sys = sysMapper.selectByLast();
        Integer unhandleCutPerStep = sys.getUnhandleCutPerStep();
        wShop.setScore(wShop.getScore() - unhandleCutPerStep);
        shopMapper.updateByPrimaryKeySelective(wShop);
        WUser wUser = userMapper.selectByPrimaryKey(wShop.getUserId());
        demand.setStatus((short) 20);
        String alert = "已取消,订单编号【" + demand.getOrderNo() + "】,扣除服务分:" + unhandleCutPerStep + "分!";
        pushService.pushShop(alert, wUser.getPhone());
        log.info(alert);

        demand.setShopId(null);
        demand.setOperateUid(null);
        demand.setStatus((short) 0);
        demandMapper.updateByPrimaryKey(demand);

        //开始记录取消日志
        DemandCancleLog log = new DemandCancleLog();
        log.setContent(alert);
        log.setDemandId(demand.getId());
        log.setShopId(demand.getShopId());
        log.setType(1);
        log.setUserId(demand.getUserId());
        demandCancleLogMapper.insertSelective(log);

        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    /**
     * 超期未处理
     *
     * @param orderId
     */
    @Transactional
    public void notifyUnHandleDemand(String orderId) {
        //检查当前订单状态
        Integer orderIdInt = Integer.valueOf(orderId);
        Demand demand = demandMapper.selectByPrimaryKey(orderIdInt);
        if (demand == null) {
            log.error("超期未处理订单【{}】不存在,请核实！", orderId);
            return;
        }

        if (demand.getStatus().intValue() > 1) {
            log.info("超期未处理订单【{}】已被处理,请核实！", orderId);
            return;
        }

        log.info("订单【{}】超期未处理", orderId);
        WShop wShop = shopMapper.selectByPrimaryKey(demand.getShopId());
        //开始扣除服务分
        Sys sys = sysMapper.selectByLast();
        Integer unhandleCutPerStep = sys.getUnhandleCutPerStep();
        wShop.setScore(wShop.getScore() - unhandleCutPerStep);
        shopMapper.updateByPrimaryKeySelective(wShop);
        // todo 推送平台账号
        //推送店铺账号
        WUser wUser = userMapper.selectByPrimaryKey(wShop.getUserId());
        String alert = "订单编号【" + demand.getOrderNo() + "】已超期,扣除服务分:" + unhandleCutPerStep + "分!";
        pushService.pushShop(alert, wUser.getPhone());
        log.info(alert);
    }


    /**
     * 每天23点50分做一次清理超期订单的操作
     * 如:超期时,服务停止的未通知的数据
     */
    public void clearUnHandle() {
        //查询
        List<Demand> demands = demandMapper.selectByStatus(1);
        Sys sys = sysMapper.selectByLast();
        Integer outOfUnhandleHours = sys.getOutOfUnhandleHours();
        //开启5个线程处理
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < demands.size(); i++) {
            Demand demand = demands.get(i);
            if (demand.getStatus().intValue() > 1) {
                log.info("超期未处理订单【{}】已被处理,请核实！", demand.getId());
                return;
            }
            Date lastUpdateTime = demand.getLastUpdateTime();
            Instant inst2 = lastUpdateTime.toInstant();
            Instant inst1 = Instant.now();
            long hours = Duration.between(inst1, inst2).toHours();
            if (hours > outOfUnhandleHours) {
                fixedThreadPool.execute(() -> {
                    notifyUnHandleDemand(demand.getId() + "");
                });
            }

        }
        log.info("后台任务提交结束,待处理数:{}！", demands.size());
    }


    /**
     * 用户评价列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public ServerResponse commentList(int pageNo, int pageSize) {
        WUser user = UserContext.getUser();
        Page<Demand> page = new Page<>(pageNo, pageSize);
        String type = "11,12,13";
        page.setRecords(demandMapper.selectByPage(page, user.getId(), null, null, null, type));
        return ServerResponse.createBySuccess(page);
    }

    public ServerResponse addShopBalance(DemandShopPayFlow demandCustomerPayFlow) {
        demandShopPayFlowMapper.insertSelective(demandCustomerPayFlow);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }


    public ServerResponse commentListForShop(String type, String keyword, int pageNo, int pageSize) {
        if (StringUtils.isEmpty(type)) {
            return ServerResponse.createByErrorMessage("请提交type!");
        }

        if (!types.contains(type)) {
            return ServerResponse.createByErrorMessage("状态有误!");
        }

        WUser user = UserContext.getUser();
        Page<Demand> page = new Page<>(pageNo, pageSize);
        List<Demand> records = demandMapper.selectByPage(page, null, user.getSId(), null, keyword, type);
        for (Demand demand : records) {
            demand.setComprehensiveStar(0);
            DemandComment demandComment = demandCommentMapper.selectByItemId(demand.getId());
            if (demandComment != null) {
                demand.setComprehensiveStar(demandComment.getComprehensiveStar());
            }
        }

        page.setRecords(records);
        return ServerResponse.createBySuccess(page);
    }

    public ServerResponse commentForCustomer(DemandTalk demandTalk) {
        if (demandTalk == null) {
            return ServerResponse.createByErrorMessage("参数有误,请核实!");
        }
        Demand demand = demandMapper.selectByPrimaryKey(demandTalk.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单已被删除,请核实!");
        }

        if (StringUtils.isEmpty(demandTalk.getContent())) {
            return ServerResponse.createByErrorMessage("请填写评论内容!");
        }

        WUser user = UserContext.getUser();

        //添加留言信息
        DemandTalk talk = new DemandTalk();
        talk.setDemandId(demand.getId());
        talk.setShopId(demand.getShopId());
        talk.setContent(demandTalk.getContent());
        talk.setType(2);
        talk.setUid(user.getId());
        talkMapper.insertSelective(talk);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    public ServerResponse commentForManage(DemandTalk demandTalk) {
        if (demandTalk == null) {
            return ServerResponse.createByErrorMessage("参数有误,请核实!");
        }
        Demand demand = demandMapper.selectByPrimaryKey(demandTalk.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单已被删除,请核实!");
        }

        if (StringUtils.isEmpty(demandTalk.getContent())) {
            return ServerResponse.createByErrorMessage("请填写评论内容!");
        }

        WUser user = UserContext.getUser();

        //添加留言信息
        DemandTalk talk = new DemandTalk();
        talk.setDemandId(demand.getId());
        talk.setShopId(demand.getShopId());
        talk.setContent(demandTalk.getContent());
        talk.setType(0);
        talk.setUid(user.getId());
        talkMapper.insertSelective(talk);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    public ServerResponse commentForShop(DemandTalk demandTalk) {
        if (demandTalk == null) {
            return ServerResponse.createByErrorMessage("参数有误,请核实!");
        }

        Demand demand = demandMapper.selectByPrimaryKey(demandTalk.getDemandId());
        if (demand == null) {
            return ServerResponse.createByErrorMessage("订单已被删除,请核实!");
        }

        if (StringUtils.isEmpty(demandTalk.getContent())) {
            return ServerResponse.createByErrorMessage("请填写评论内容!");
        }

        WUser user = UserContext.getUser();

        //添加留言信息
        DemandTalk talk = new DemandTalk();
        talk.setDemandId(demand.getId());
        talk.setShopId(demand.getShopId());
        talk.setContent(demandTalk.getContent());
        talk.setType(1);
        talk.setUid(user.getId());
        talkMapper.insertSelective(talk);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }
}
